package com.mobilepay.moneypig.model.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.DIR;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.activity.about.AboutActivity;
import com.mobilepay.moneypig.model.activity.launcher.LoginActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.update.AppUpdate;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.LogDebug;
import com.mobilepay.moneypig.utils.SysUtil;
import com.mobilepay.moneypig.view.WebViewActivity;

import java.io.File;

/**
 * Created by xlm on 2017/7/25 0025
 */

public class MineSetupActivity extends BaseActivity {
    private static final String TAG = "MineSetupActivity";
    private RelativeLayout mRelativeBack;
    private RelativeLayout mRelativePassWord;
    private RelativeLayout mRelativeMobile;
    private RelativeLayout mRelativeAbout;
    private RelativeLayout mRelativeXieyi;
    private RelativeLayout mRelativeExit;
    private RelativeLayout mRelativeVersion;
    private TextView mTextVersion;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_setup);
    }

    @Override
    protected void initViews() {
        mRelativeBack = (RelativeLayout) findViewById(R.id.setup_back);
        mRelativePassWord = (RelativeLayout) findViewById(R.id.setup_change_password);
        mRelativeMobile = (RelativeLayout) findViewById(R.id.setup_change_mobile);
        mRelativeAbout = (RelativeLayout) findViewById(R.id.setup_change_about);
        mRelativeXieyi = (RelativeLayout) findViewById(R.id.setup_change_xieyi);
        mRelativeExit = (RelativeLayout) findViewById(R.id.setup_change_exit);
        mRelativeVersion = (RelativeLayout) findViewById(R.id.setup_version);
        mTextVersion = (TextView) findViewById(R.id.txt_version);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        mTextVersion.setText(String.format(getString(R.string.app_version), CommonUtil.getVersionName(getThis())));
    }

    @Override
    protected void onSetListener() {
        mRelativeAbout.setOnClickListener(this);
        mRelativePassWord.setOnClickListener(this);
        mRelativeMobile.setOnClickListener(this);
        mRelativeAbout.setOnClickListener(this);
        mRelativeXieyi.setOnClickListener(this);
        mRelativeExit.setOnClickListener(this);
        mRelativeBack.setOnClickListener(this);
        mRelativeVersion.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setup_back:
                finish();
                break;
            case R.id.setup_change_password://修改密码
                startActivity(ChangePassWord.class, false, false);
                break;
            case R.id.setup_change_mobile:
                startActivity(ChangeMobileActivity.class, false, false);
                break;
            case R.id.setup_change_about:
                startActivity(AboutActivity.class, false, false);
                break;
            case R.id.setup_change_xieyi:
                Intent intent2 = new Intent();
                intent2.setClass(getThis(), WebViewActivity.class);
                intent2.putExtra(Key.TITLE, "用户协议");
                intent2.putExtra(Key.URL, NetConfig.USER_DOCUMENT);
                startActivity(intent2);
                break;
            case R.id.setup_change_exit:
                showExitDialog();
                break;
            case R.id.setup_version:
                checkVersonUpdate();
                break;
        }
    }

    private TipDialog mDialogExit;

    private void showExitDialog() {
        if (mDialogExit == null) {
            mDialogExit = new TipDialog(this);
        }
        mDialogExit.setContent("确认退出登录?");
        mDialogExit.setCancelable(true);
        mDialogExit.setListener(new TipDialog.Listener() {
            @Override
            public void onDismiss() {
                mDialogExit.cancel();
            }

            @Override
            public void onConfirm() {
                mDialogExit.dismiss();
                unbindGetui();
            }
        });
        mDialogExit.show();
    }

    private void unbindGetui() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getui_unbind);
        param.add("uid", String.valueOf(App.getApp().getUserDetailInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                exitApp();
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
//                showToastShort(string);
                exitApp();
            }
        });
    }

    private void exitApp() {
        PushManager.getInstance().stopService(getApplicationContext());//关闭个推sdk
        Intent intent = new Intent(MineSetupActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getApp().cancelAccount();//注销
        startActivity(intent);
    }

    private String mApkUrl;
    private String mUpdateVersion;

    /**
     * 检查版本更新
     */
    private void checkVersonUpdate() {
        final String mCurrentVersion = CommonUtil.getVersionName(App.getApp());
        HttpUtils.RequestParam params = new HttpUtils.RequestParam();
        params.add("method", NetConfig.updateApk);
        params.add("client_version", mCurrentVersion);
        params.add("client_type", "ANDROID");
        params.add("sign", params.getMd5String());
        HttpUtils.getInstance().params(params).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(MineSetupActivity.this)) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        AppUpdate appUpdate = GsonUtil.GsonToBean(string, AppUpdate.class);
                        mApkUrl = appUpdate.getData().getAndroid_download();
                        mUpdateVersion = appUpdate.getData().getAndroid_version();
                        //是否更新
                        if (!mCurrentVersion.equals(mUpdateVersion)) {
                            File dir = new File(DIR.TEMP_APK);
                            if (dir.exists()) {
                                File[] files = dir.listFiles();
                                for (File file : files) {
                                    if (file.getName().contains(".apk")) {
                                        try {
                                            CommonUtil.deleteFile(file);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            foundUpdate();
                        } else {
                            showToastShort("当前已是最新版本");
                        }
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private void foundUpdate() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showUpdateTip();
            }
        });
    }

    //下载应用
    private void downLoadApk() {
        HttpUtils.getInstance().loadFile(mApkUrl, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
            }

            @Override
            public void onResponseProgress(long progress, long total, boolean done) {
                float per = (float) progress / (float) total * (float) 100;
                String pers = String.valueOf(per);
                if (pers.length() > 5) {
                    pers = pers.substring(0, 5);
                }
                final String finalPers = pers;
                showDownProgress("正在下载" + " " + finalPers + "%");
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                showDownProgress("准备安装，请稍后");
                String savepath = DIR.TEMP_APK + "/" + mUpdateVersion + ".apk";
                File file = new File(savepath);
                try {
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    dismissDownProgress();
                    SysUtil.installApk(App.getApp(), file.getPath());
                } catch (Exception e) {
                    LogDebug.e(e);
                }
            }
        });
    }

    private TipDialog mUpdateTip;

    private void showUpdateTip() {
        if (mUpdateTip == null) {
            mUpdateTip = new TipDialog(this);
            mUpdateTip.setContent("发现新版，是否更新？");
            mUpdateTip.setCancle("否");
            mUpdateTip.setConfirm("是");
            mUpdateTip.setCancelable(true);
            mUpdateTip.setListener(new TipDialog.Listener() {
                @Override
                public void onConfirm() {
                    downLoadApk();
                }

                @Override
                public void onDismiss() {
                    super.onDismiss();
                    mUpdateTip.dismiss();
                }
            });
        }
        mUpdateTip.show();
    }
}
